package pro.reznick.geoalarm;

import java.util.List;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class AlarmDataAdapter extends BaseAdapter {

	List<AlarmData> alarms;

	LayoutInflater inflater;
    private GeoAlarmController controller;

    public AlarmDataAdapter(List<AlarmData> alarms, LayoutInflater inflater, GeoAlarmController controller) {

		this.inflater = inflater;
        this.controller = controller;
        setAlarms(alarms);
	}

	private void setAlarms(List<AlarmData> alarms) {
		this.alarms = alarms;
	}

	@Override
	public int getCount() {
		return alarms.size();
	}

	@Override
	public Object getItem(int index) {
		return alarms.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		final AlarmData current = alarms.get(position);
        boolean converted = false;
		View v = null;
		if (convertView == null) {
			v = inflater.inflate(R.layout.alarm_list_item, null);
		} else {
			v = convertView;
            converted = true;
		}

		v.setClickable(true);
		ToggleButton tglAlarm = (ToggleButton) v.findViewById(R.id.tglAlarm);
        if (converted)
            tglAlarm.setOnCheckedChangeListener(null);
        tglAlarm.setChecked(current.isOn());
		TextView txtName = (TextView) v.findViewById(R.id.txtName);
		TextView txtCoords = (TextView) v.findViewById(R.id.txtCoords);
		txtName.setText(current.getName());
		txtCoords.setText(String.format("%5f,%5f", current.getLatitude(),
				current.getLongitude()));

        tglAlarm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b)
            {
                controller.setAlarmState(current, b);
            }
        });
		return v;

	}

	public void add(AlarmData alarm) {
		alarms.add(alarm);
		notifyDataSetChanged();
	}

	

	public void refresh(List<AlarmData> newAlarms) {
		setAlarms(newAlarms);
		notifyDataSetChanged();

	}

}
